package com.lelefly.base.controller;

import java.math.BigDecimal;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.List;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.commons.lang.StringUtils;
import org.springframework.dao.DataAccessException;
import org.springframework.jdbc.core.BatchPreparedStatementSetter;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.lelefly.base.daoimp.BaseDao;
import com.lelefly.base.model.ActivatePlaneBean;
import com.lelefly.base.model.PlaneDetailBean;
import com.lelefly.base.model.RequestAreaBean;
import com.lelefly.base.model.RequestPlaneDetailBean;
import com.lelefly.base.model.RequestUpdateLastCountBean;
import com.lelefly.base.model.Result;
import com.lelefly.base.model.ResultVo;
import com.lelefly.base.model.RowResult;
import com.lelefly.base.model.SyncPlaneTimeBean;
import com.lelefly.base.model.UavTimeBean;
import com.lelefly.base.po.FarmlandAccess;
import com.lelefly.base.po.UavInfo;
import com.lelefly.base.po.UavInfoNew;
import com.lelefly.base.po.UavTime;
import com.lelefly.base.serviceImp.UavInfoService;
import com.lelefly.base.utils.DateUtils;
import com.lelefly.base.utils.ParamsUtils;
import com.lelefly.constant.Constant;
import com.lelefly.handleexecption.ValidateExecption;
import com.lelefly.http.SessionInfo;

@Controller
@RequestMapping("/uavinfo")
public class UavInfoController extends BaseController{

	@Resource
	public UavInfoService uavInfoService;
	
	@Resource
	private JdbcTemplate jdbcTemplate;
	
	@Resource
	private BaseDao baseDao;
	
	@RequestMapping("/updatePlaneStatus")
	@ResponseBody
	public Result updatePlaneStatus(HttpServletRequest request){
		Result result = new Result<>();
		String data = request.getParameter("data");
		System.out.println("更新状态" + data);
		Gson gson = new Gson();
		final List<UavInfoNew> list = gson.fromJson(data,new TypeToken<List<UavInfoNew>>(){}.getType());
		try {
			result.setState(Constant.HTTP_STATUS_OK);
			result.setMes("更新成功");
			String sql = "update uav_info_new a set a.last_count=?,a.isCased=? where a.uavid=?";
			jdbcTemplate.batchUpdate(sql, new BatchPreparedStatementSetter() {
				
				@Override
				public void setValues(PreparedStatement pstmt, int i) throws SQLException {
					pstmt.setString(1, list.get(i).getLastCount());
					pstmt.setString(2, list.get(i).getIsCased());
					pstmt.setString(3, list.get(i).getUavid());
				}
				
				@Override
				public int getBatchSize() {
					return list.size();
				}
			});
		} catch (DataAccessException e) {
			e.printStackTrace();
			result.setState(Constant.HTTP_STATUS_FAIL);
			result.setMes("更新失败");
		}
		return result;
	}

	@SuppressWarnings({ "rawtypes", "unchecked" })
	@RequestMapping(value="/getUavInfo",produces="application/json;charset=utf-8")
	@ResponseBody
	public Result getFarmlandAccesss(String uavHaver){
		Result<UavInfo> result=null;
		try {
			result = uavInfoService.getUavInfo(uavHaver);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			getLogger().info("----->>"+e.getLocalizedMessage());
		}
		return result;
	}
	
	
	
	@SuppressWarnings({ "rawtypes", "unchecked" })
	@RequestMapping(value="/adduavinfo",produces="application/json;charset=utf-8")
	@ResponseBody
	public ResultVo adduavinfo(UavInfo uavInfo){
		ResultVo result = new ResultVo();
		result.setStatus("false");
		try {
			ParamsUtils.checkParams(uavInfo.getUavType(),uavInfo.getMode());
			uavInfo.setUpdateTime(DateUtils.getCurDate());
			baseDao.saveObject(uavInfo);
			result.setStatus("true");
		} catch (Exception e) {
			// TODO Auto-generated catch block
			getLogger().info("----->>"+e.getLocalizedMessage());
		}catch (ValidateExecption e) {
			// TODO: handle exception
			result.setError(e.mes);
		}
		return result;
	} 
	
	@SuppressWarnings({ "rawtypes", "unchecked" })
	@RequestMapping(value="/updateUavInfo",produces="application/json;charset=utf-8")
	@ResponseBody
	public Result updateUavInfo(UavInfo uavInfo){
		Result<FarmlandAccess> result=null;
		try {
			result = uavInfoService.updateUavInfo(uavInfo);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			getLogger().info("----->>"+e.getLocalizedMessage());
		}
		return result;
	}
	
	@SuppressWarnings({ "rawtypes", "unchecked" })
	@RequestMapping(value="/delUavInfo",produces="application/json;charset=utf-8")
	@ResponseBody
	public Result delUavInfo(String uavnm){
		Result<FarmlandAccess> result=null;
		try {
			result = uavInfoService.delUavInfo(uavnm);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			getLogger().info("----->>"+e.getLocalizedMessage());
		}
		return result;
	}
	
	@SuppressWarnings({ "rawtypes", "unchecked" })
	@RequestMapping(value="/updateuavhaver")
	@ResponseBody
	public ResultVo updateUavHaver(String id , String haverid){
		ResultVo result  = new ResultVo();
		result.setStatus("false");
		String sql = "select count(*) from uavinfo where id =?";
		String updatesql = "update uavinfo set haver_id =? where id=?";
		try {
			ParamsUtils.checkParams(id,haverid);
			int  count= jdbcTemplate.queryForInt(sql, new Object[]{Integer.valueOf(id)});
			if (count==0) {
				throw new ValidateExecption("要修改的无人机不存在");
			}
			jdbcTemplate.update(updatesql,haverid,id);
			result.setStatus("true");
		} catch (Exception e) {
			// TODO Auto-generated catch block
			getLogger().info("----->>"+e.getLocalizedMessage());
		}catch (ValidateExecption e) {
			// TODO: handle exception
			result.setError(e.mes);
		}
		return result;
	}
	
	
	public ResultVo updateUavlastCount(String id , String lastcount){
		ResultVo result  = new ResultVo();
		result.setStatus("false");
		String sql = "select count(*) from uav_info_new where uavid =?";
		String updatesql = "update uav_info_new set last_count =? "+" where uavid=?";
		try {
			ParamsUtils.checkParams(id,lastcount);
			int  count= jdbcTemplate.queryForInt(sql, new Object[]{id});
			if (count==0) {
				throw new ValidateExecption("要修改的无人机不存在");
			}
			jdbcTemplate.update(updatesql,lastcount,id);
			result.setStatus("true");
		} catch (Exception e) {
			// TODO Auto-generated catch block
			getLogger().info("----->>"+e.getLocalizedMessage());
		}catch (ValidateExecption e) {
			// TODO: handle exception
			result.setError(e.mes);
		}
		return result;
	}
	
	@RequestMapping(value="/updateuavlastcount")
	@ResponseBody
	public ResultVo updateUavlastCount(RequestUpdateLastCountBean bean){
		String id = bean.getId();
		String lastcount = bean.getLastcount();
		ResultVo result = updateUavlastCount(id, lastcount);
		return result;
	}
	
	
	@SuppressWarnings({ "rawtypes", "unchecked" })
	@RequestMapping(value="/updateuavmode")
	@ResponseBody
	public ResultVo updateUavmode(String id , String mode){
		ResultVo result  = new ResultVo();
		result.setStatus("false");
		String sql = "select count(*) from uavinfo where id =?";
		String updatesql = "update uavinfo set mode = ? , update_time=? where id=?";
		try {
			ParamsUtils.checkParams(id,mode);
			int  count= jdbcTemplate.queryForInt(sql, new Object[]{Integer.valueOf(id)});
			if (count==0) {
				throw new ValidateExecption("要修改的无人机不存在");
			}
           if (mode.equals("0")||mode.equals("-1")) {
        	   jdbcTemplate.update(updatesql,mode,DateUtils.getCurDate());
			}else {
				throw new ValidateExecption("模式错误");
			}
			result.setStatus("true");
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			getLogger().info("----->>"+e.getLocalizedMessage());
		}catch (ValidateExecption e) {
			// TODO: handle exception
			result.setError(e.mes);
		}
		return result;
	}
	
	/**
	 * 飞机激活
	 * @param planeBean
	 * @return
	 */
	@RequestMapping(value="/activate_plane")
	@ResponseBody
	public Result activatePlane(ActivatePlaneBean planeBean){
		
		Result result = new Result<>();
		
		if (planeBean == null
				|| StringUtils.isEmpty(planeBean.getUavid())
				|| StringUtils.isEmpty(planeBean.getUavActivater())
				|| StringUtils.isEmpty(planeBean.getDistributorPhoneNo())
				|| StringUtils.isEmpty(planeBean.getCode())) {
			result.setMes("必输参数为空");
			result.setState(Constant.HTTP_STATUS_FAIL);
			return result;
		}
		
		result = uavInfoService.activatePlane(planeBean);
		return result;
		
	}
	
	@RequestMapping(value="/get_my_plane")
	@ResponseBody
	public Result<UavInfoNew> getMyPlane(@RequestBody String phoneNo){
		Result<UavInfoNew> result = new Result<>();
		
		if (StringUtils.isEmpty(phoneNo)) {
			
			result.setState(Constant.HTTP_STATUS_FAIL);
			result.setMes("手机号为空！");
			return result;
		}
		result = uavInfoService.getMyPlane(phoneNo);
		return result;
	}
	
	@RequestMapping("/query_plane_detail")
	@ResponseBody
	public Result<PlaneDetailBean> queryPlaneDetail(RequestPlaneDetailBean bean){
		Result<PlaneDetailBean> result = new Result<>();
		if (bean == null || StringUtils.isEmpty(bean.getPhoneNo())
				|| StringUtils.isEmpty(bean.getPlaneId())) {
			result.setMes("必输项不能为空");
			result.setState(Constant.HTTP_STATUS_FAIL);
			return result;
		}
		result = uavInfoService.queryPlaneDetail(bean);
		return result;
	}
	
	@RequestMapping("/query_fly_area")
	@ResponseBody
	public Result<BigDecimal> queryFlyArea(RequestAreaBean bean){
		Result<BigDecimal> result = new Result<>();
		if (bean == null || StringUtils.isEmpty(bean.getBeginTime())
				|| StringUtils.isEmpty(bean.getEndTime())
				|| StringUtils.isEmpty(bean.getPlaneId())) {
			result.setMes("必输项不能为空");
			result.setState(Constant.HTTP_STATUS_FAIL);
			return result;
		}
		result = uavInfoService.queryFlyArea(bean);
		return result;
	}
	
	/**
	 * 设置飞机剩余时间
	 * @param bean
	 * @return
	 */
	@RequestMapping("/update_uav_left_time")
	@ResponseBody
	public Result setUavLeftTime(UavTimeBean bean){
		Result result = new Result<>();
		if (bean == null || StringUtils.isEmpty(bean.getUavId())
				|| StringUtils.isEmpty(bean.getPassword())) {
			result.setState(Constant.HTTP_STATUS_FAIL);
			result.setMes("必输项不能为空！");
			return result;
		}
		result = uavInfoService.updateLeftTime(bean);
		return result;
	}
	
	/**
	 * 查询飞机剩余时间
	 * @param bean
	 * @return
	 */
	@RequestMapping("/query_uav_left_time")
	@ResponseBody
	public Result queryUavLeftTime(UavTimeBean bean){
		Result result = new Result<>();
		if (bean == null || StringUtils.isEmpty(bean.getUavId())
				|| StringUtils.isEmpty(bean.getPassword())) {
			result.setState(Constant.HTTP_STATUS_FAIL);
			result.setMes("参数错误");
			return result;
		}
		result = uavInfoService.queryUavLeftTime(bean);
		return result;
	}
	
	/**
	 * 同步飞机飞行时间
	 * @return
	 */
	@RequestMapping("/sync_plane_time")
	@ResponseBody
	public Result<UavTime> syncPlaneTime(SyncPlaneTimeBean bean){
		Result<UavTime> result = new Result<>();
		if (bean == null || StringUtils.isEmpty(bean.getUavId())) {
			result.setState(Constant.HTTP_STATUS_FAIL);
			result.setMes("飞机ID不能为空");
			return result;
		}
		result = uavInfoService.syncPlaneTime(bean);
		return result;
	}
	
	/**
	 * 锁定飞机
	 * @param bean
	 * @return
	 */
	@RequestMapping("/lock_uav")
	@ResponseBody
	public Result lockUav(UavTimeBean bean){
		Result result = new Result<>();
		if (bean == null || StringUtils.isEmpty(bean.getUavId())
				|| StringUtils.isEmpty(bean.getPassword())) {
			result.setState(Constant.HTTP_STATUS_FAIL);
			result.setMes("参数错误");
			return result;
		}
		result = uavInfoService.lockUav(bean);
		return result;
	}
	
	@RequestMapping("/get_distributor_plane")
	@ResponseBody
	public RowResult<UavInfoNew> getDistributorPlane(HttpSession httpSession,HttpServletRequest request){
		RowResult<UavInfoNew> result = new RowResult<>();
		SessionInfo info = (SessionInfo) httpSession.getAttribute(Constant.SESSION_INFO);
		if (info == null) {
			result.setTotal(0);
			return result;
		}
		String phoneNum = info.getPhoneNum();
		String limit = request.getParameter("limit");
		String start = request.getParameter("start");
		result = uavInfoService.getDistributorPlane(phoneNum,start,limit);
		return result;
	}
	
}
